import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'

export function useI18n(translationFile: string) {
  const { i18n, t } = useTranslation(translationFile)
  const [languageLoaded, setLanguageLoaded] = useState(false)
  const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
  const loadTranslations = async () => {
    await delay(1000)
    setLanguageLoaded(true)
  }

  useEffect(() => {
    loadTranslations()
  }, [])

  useEffect(() => {
    const i18nChange = () => {
      setLanguageLoaded(false)
      loadTranslations()
    }
    i18n.on('languageChanged', i18nChange)
    return () => {
      i18n.off('languageChanged', i18nChange)
    }
  }, [i18n, translationFile])

  return { languageLoaded, t }
}
